package com.bigfish.gbs.service.impl;

import com.bigfish.gbs.dao.OrderInfoMapper;
import com.bigfish.gbs.dao.OrderItemMapper;
import com.bigfish.gbs.dto.OrderItemVO;
import com.bigfish.gbs.dto.Result;
import com.bigfish.gbs.entity.OrderInfo;
import com.bigfish.gbs.entity.OrderItem;
import com.bigfish.gbs.enums.ResultEnum;
import com.bigfish.gbs.exception.MyException;
import com.bigfish.gbs.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @Author Joycessh
 * @Description
 * @Date 12/24/18 9:42 AM
 */
@Service("OrderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public Long createOrder(List<OrderItem> list) {

        BigDecimal sum = new BigDecimal(0);
//        list.forEach(orderItem -> {
//            int i = orderItem.getQuantity(); //数量
//            BigDecimal j = orderItem.getCurrentUnitPrice(); //单价
//            BigDecimal g = j.multiply(new BigDecimal(i));
//            sum = sum.add(g);
//            System.out.println("sum:" + sum);
//        });
        for (OrderItem orderItem : list) {
            int i = orderItem.getQuantity(); //数量
            BigDecimal j = orderItem.getCurrentUnitPrice(); //单价
            BigDecimal g = j.multiply(new BigDecimal(i));
            sum = sum.add(g);
            System.out.println("sum:" + sum);
        }

        String userId = list.get(0).getUserId();
        System.out.println(userId);

        if (userId == null) {
            throw new MyException(ResultEnum.FAIL);
        }

        OrderInfo order = new OrderInfo();
        order.setPayment(sum);
        order.setUserId(userId);
        order.setPaymentType(1); // 1: 在线支付
        order.setStatus(10); //订单状态:0-已取消-10-未付款，20-已付款，40-已发货，50-交易成功，60-交易关闭
        order.setPostage(0); // 运费
        orderInfoMapper.insertSelective(order);

        Long orderId = order.getOrderId();
        list.forEach(orderItem -> {
            orderItem.setOrderId(orderId);
            orderItemMapper.insertSelective(orderItem);
        });

        return orderId;
    }

    @Override
    public List<OrderItemVO> getOrderList(String userId) {
        return orderItemMapper.selectByUserId(userId);
    }

    @Override
    public Result manageList(int pageNum, int pageSize) {
        return null;
    }

    @Override
    public Result manageDetail(Long orderNo) {
        return null;
    }

    @Override
    public Result manageSearch(Long orderNo, int pageNum, int pageSize) {
        return null;
    }

    @Override
    public Result manageSendGoods(Long orderNo) {
        return null;
    }

    @Override
    public List<OrderInfo> getOrders() {
        return orderInfoMapper.selectOrder();
    }
}
